#ifndef __GSHTTPGATEWAY_H__
#define __GSHTTPGATEWAY_H__

#if _MSC_VER > 1000
# pragma once
#endif

#include "INetworkService.h"
#include "GameSpy/ghttp/ghttp.h"


class CGSHTTPGateway : public CMultiThreadRefCount, public IHTTPGateway
{
private:
	struct SHTTPJob
	{
		GHTTPRequest				request;
		std::vector<uint8>	data;
		GHTTPResult					result;
		int									id;
		CGSHTTPGateway*			owner;
	};

	struct SUploadFile
	{
		std::vector<uint8>	data;
		string							mime;
		string							name;
	};
	typedef std::map<int, SHTTPJob>			TJobMap;
	typedef std::map<int, SUploadFile>	TFileMap;
public:
	CGSHTTPGateway();
	~CGSHTTPGateway();

	virtual int GetURL(const char* url, IDownloadStream* stream);
	virtual int PostURL(const char* url, const char* params, IDownloadStream* stream);
	virtual int PostFileToURL(const char* url, const char* params, const char* name, const uint8* data, uint32 size, const char* mime, IDownloadStream* stream);
	virtual void CancelRequest(int id);

	bool IsDead()const{return false;}
	
protected:
	void NC_GetURL(int id, string url);
	void NC_PostURL(int id, string url, string params, SUploadFile* pFile);
	void NC_CancelRequest(int id);

	void GC_Completed(int id, uint8* data, uint32 size, bool success);

	static GHTTPBool CompletedCallback( GHTTPRequest request, GHTTPResult result, char * buffer, GHTTPByteCount bufferLen, void * param ); 
	static void ProgressCallback( GHTTPRequest request, GHTTPState state, const char * buffer, GHTTPByteCount bufferLen, GHTTPByteCount bytesReceived, GHTTPByteCount totalSize, void * param ); 

	static void TimerCallback( NetTimerId id, void * pUser, CTimeValue tm );

	void CleanUp();

private:
	std::map<int, IDownloadStream*> m_callbacks;
	TJobMap		m_requests;
	TFileMap	m_filedata;
	int	m_lastId;
	NetTimerId  m_updateTimer;
};

#endif //__GSHTTPGATEWAY_H__